<?php

namespace app\admin\controller\kefu;

use Throwable;
use app\worker\library\kefu\Common;
use app\common\controller\Backend;

/**
 * 用户轨迹管理
 */
class Trajectory extends Backend
{
    /**
     * Trajectory模型对象
     * @var object
     * @phpstan-var \app\admin\model\kefu\Trajectory
     */
    protected object $model;

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected array $withJoinTable = ['user'];

    protected string|array $quickSearchField = ['id', 'title', 'details', 'url'];

    public function initialize(): void
    {
        parent::initialize();
        $this->model = new \app\admin\model\kefu\Trajectory();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {
        // 如果是 select 则转发到 select 方法，若未重写该方法，其实还是继续执行 index
        if ($this->request->param('select')) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->visible(['user' => ['nickname']])
            ->paginate($limit)
            ->each(function ($item) {
                if ($item->user_id && $item->user) {
                    $item->user->nickname = Common::trueValue([
                        $item->user->nickname,
                        $item->user->admin?->nickname,
                        $item->user->sysUser?->nickname,
                        Common::getTouristNickname($item->user->id),
                    ]);
                }
            });

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }
}